package org.example.onlineEducation.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.onlineEducation.dao.UserDao;
import org.example.onlineEducation.entity.User;
import org.example.onlineEducation.utils.JWTUtils;
import org.example.onlineEducation.utils.LoginUser;
import org.example.onlineEducation.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private MenuService menuService;

    public Result login(User user){

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        if(Objects.isNull(authentication)){
            return Result.end(401, null, "用户名或者密码错误！");
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        System.out.println("登录操作：\n" + loginUser);

        Map<String, Object> map = new HashMap<>();

        user = loginUser.getUser();
        user.setPassword(null);
        map.put("user",user);
        map.put("menus", menuService.selectAllByRoleId(user.getRoleId()));
        map.put("token", JWTUtils.createToken(String.valueOf(user.getId()), JSONArray.toJSONString(loginUser.getAuthorities(), true)));

        return Result.success(map);
    }
}
